const app = getApp(),
    config = require('./config').config,
    md5 = require('./md5')

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
        }
    }
    return fmt
}

/**
 * 对象数组去重
 * @param {String} key
 */
Array.prototype.reduceRepeat = function (key) {
    if (!key) return this

    let arr = this,
        newArr = [],
        identify = []

    arr.forEach((o, index) => {
        if (identify.indexOf(o[key]) === -1) {
            identify.push(o[key])
            newArr.push(o)
        } else if (!o[key]) {
            newArr.push(o)
        }
    })

    return newArr
}

/**
 * 获取两个页面之间的delta，如果包含主页，则不适用
 * @param {对比页面的url} url
 */
const getPageDelta = url => {
    let curPages = getCurrentPages(),
        len = curPages.length

    for (let i = 0; i < len; i++) {
        if (curPages[i].route === url) {
            return (len - 1) - i
        }
    }

    return -1
}

const wxMd = {
    showModal(opts) {
        let defOpts = {
            title: '提示',
            content: '消息',
            showCancel: false
        },
            newOpts = Object.assign({}, defOpts, opts)
        wx.showModal(newOpts)
    },
    showLoading(opts) {
        let defOpts = {
            title: '加载中',
            mask: true
        },
            newOpts = Object.assign({}, defOpts, opts)
        wx.showLoading(newOpts)
    },
    hideLoading() {
        wx.hideLoading()
    },
    showToast(opts) {
        let defOpts = {
            title: '',
            mask: true
        },
            newOpts = Object.assign({}, defOpts, opts)
        wx.showToast(newOpts)
    }
}

const tinyWxHeadImg = url => {
    if (typeof url != "string") {
        return false;
    }
    let pos = url.length - 2,
        backStr = url.substring(pos),
        result = url;
    if (backStr === "/0") {
        result = url.substring(0, pos) + "/96";
    }
    return result;
}

function replaceResPath(path) {
    return path
        .replace(/\*_resRoot\*/g, config.staticResPath + "/image/mobile/newgame")
        .replace(/\*_qiniuResRoot\*/g, config.userImagePath);
}
//解析富文本时对富文本的图片处理
function formatImg(html) {
    var newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        var classReg = new RegExp(/class=['|\"]([^\'\"]*)['|\"]/i);
        var styleReg = new RegExp(/style=['|\"]([^\'\"]*)['|\"]/i);
        if (styleReg.test(match)) {
            match = match.replace(styleReg, function (m, captrue) {
                return m.substring(0, m.length - 1) + " max-width:100%;" + m.substring(m.length - 1);
            });
        }
        if (classReg.test(match)) {
            match = match.replace(classReg, function (m, captrue) {
                return m.substring(0, m.length - 1) + " img-responsive" + m.substring(m.length - 1);
            });
        } else {
            var srcIndex = match.indexOf("src=");
            return match.substring(0, srcIndex) + " class='img-responsive' " + match.substring(srcIndex);
        }
        return match;
    });
    return newContent;
}
// 解析有娱gamePageJson字段
const getGamePageJson = gamePageJson => {
    var pageJson = {};
    for (let key in gamePageJson) {
        if (key.indexOf("propList") === -1) {
            if (typeof gamePageJson[key] === "string") {
                pageJson[key] = replaceResPath(gamePageJson[key]);
            } else if (typeof gamePageJson[key] === "object") {
                pageJson[key] = replaceResPath(gamePageJson[key].path);
            }
        } else {
            let propList = JSON.parse(gamePageJson[key]);
            for (let i = 0; i < propList.length; i++) {
                let prop = propList[i];
                pageJson[prop.name] = replaceResPath(prop.path[0][0]);
            }
        }
    }
    return pageJson;
}

/**
 * 获取整型随机数
 */
const getIntRandom = (start, end) => {
    return Math.floor(Math.random() * (end - start)) + start
}

/**
 * 生成密钥相关信息
 */
const buildSecret = (key = '', value = '') => {
    let random = getIntRandom(10000000, 99999999),
        time = Date.now() - app.globalData.serverDeltaTime,
        sign = md5.hexMD5('' + random + time + config.secretKey + value),
        res = ''

    res = `${time};${sign};${random};`

    if(key) {
        res += (key + ';')
    }

    return res
}

function buildKey(fileSuffix, directoryName) {
    let d = new Date(),
        year = d.getFullYear(),
        month = d.getMonth() + 1,
        day = d.getDate()

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }

    function guid() {
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4())
    }

    let nameKey = guid() + '.' + fileSuffix,
        key = `${directoryName}/${year}/${month}/${day}/${nameKey}`

    return key
}

//文本转html
function replaceTextToHtml(txt) {
  if (!txt) return ''
  var strArr = txt.split(/\n/),
    html = ''
  strArr.forEach(str => {
    html += `<p>${str ? str : '<br>'}</p>`
  })
  return html
}


module.exports = {
    getPageDelta,
    tinyWxHeadImg,
    wxMd,
    getGamePageJson,
    formatImg,
    getIntRandom,
    buildSecret,
    buildKey,
    replaceTextToHtml,
}
